Telegram Group & Telegram Channel
🧠 Как static в C++ помогает бороться с неожиданностями

Сейчас покажу вам интересную особенность ключевого слова static в контексте функций — то, что часто забывают даже опытные разработчики.

Представим простую ситуацию:


void logCall() {
int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


Кажется, всё хорошо… Но функция всегда выводит Called 1 times, потому что переменная counter создаётся заново при каждом вызове.

Теперь добавим static:


void logCall() {
static int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


А вот теперь магия — переменная counter сохраняет своё значение между вызовами! Это отличный способ реализовать простой счётчик, кэш или ленивую инициализацию прямо в функции.

📌 Важно: static делает переменную локальной по области видимости, но глобальной по времени жизни.

А вы где применяли static неожиданным образом? Делитесь в комментариях! 👇

➡️ @cpp_geek



tg-me.com/cpp_geek/308
Create:
Last Update:

🧠 Как static в C++ помогает бороться с неожиданностями

Сейчас покажу вам интересную особенность ключевого слова static в контексте функций — то, что часто забывают даже опытные разработчики.

Представим простую ситуацию:


void logCall() {
int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


Кажется, всё хорошо… Но функция всегда выводит Called 1 times, потому что переменная counter создаётся заново при каждом вызове.

Теперь добавим static:


void logCall() {
static int counter = 0;
counter++;
std::cout << "Called " << counter << " times\n";
}


А вот теперь магия — переменная counter сохраняет своё значение между вызовами! Это отличный способ реализовать простой счётчик, кэш или ленивую инициализацию прямо в функции.

📌 Важно: static делает переменную локальной по области видимости, но глобальной по времени жизни.

А вы где применяли static неожиданным образом? Делитесь в комментариях! 👇

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/308

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

In many cases, the content resembled that of the marketplaces found on the dark web, a group of hidden websites that are popular among hackers and accessed using specific anonymising software.“We have recently been witnessing a 100 per cent-plus rise in Telegram usage by cybercriminals,” said Tal Samra, cyber threat analyst at Cyberint.The rise in nefarious activity comes as users flocked to the encrypted chat app earlier this year after changes to the privacy policy of Facebook-owned rival WhatsApp prompted many to seek out alternatives.C geek from in


Telegram C++ geek
FROM USA